import os

from flask import request

from flaskapp.exts import db
from flaskapp.entity.Book import Book
from flaskapp.entity.Consultation import Consultation
from flaskapp.entity.User import User
from flaskapp.util.Jwt import user_token_required
from flaskapp.util.Redprint import Redprint
from flaskapp.util.Result import Result

api = Redprint('admin')


@api.route('/dashboard', methods=['GET'])
@user_token_required(admin_required=True)
def dashboard(user_info):
    return '<h1>Dashboard</h1>'


# 获取所有用户信息
@api.route('/getAllusers', methods=['GET'])
@user_token_required(admin_required=True)
def getAllUser(user_info):
    users = User.query.all()
    user_list = []
    for user in users:
        user_list.append(user.to_dict())
    return Result.success(user_list)


# 获取指定用户信息
@api.route('/getUserByID/<userid>', methods=['GET', 'POST'])
@user_token_required(admin_required=True)
def findUserById(userid, user_info):
    user = User.query.get(userid)
    if user is None:
        return Result.error(404, 'User not found')
    else:
        return Result.success(user.to_dict())


# 根据用户名获取
@api.route('/getUserByName/<username>', methods=['GET', 'POST'])
@user_token_required(admin_required=True)
def findUserByName(username, user_info):
    users = User.query.filter_by(username=username).all()
    user_list = []
    if not users:
        return Result.error(404, 'User not found')
    else:
        for user in users:
            user_list.append(user.to_dict())
        return Result.success(user_list)


# 删除用户
@api.route('/deleteUser/<userid>', methods=['DELETE'])
@user_token_required(admin_required=True)
def deleteUserByID(userid, user_info):
    user = User.query.filter_by(userid=userid).first()
    if user is None:
        return Result.error(404, 'User not found')
    else:
        user.deleteUser()
        return Result.success(None, 'User deleted')


# 删除用户
@api.route('/deleteUser/<username>', methods=['DELETE'])
@user_token_required(admin_required=True)
def deleteUserByName(username, user_info):
    user = User.query.filter_by(username=username).first()
    if user is None:
        return Result.error(404, 'User not found')
    else:
        user.deleteUser()
        return Result.success(None, 'User deleted')


# 编辑用户信息
@api.route('/editUserInfo', methods=['PUT'])
@user_token_required(admin_required=False)
def editUserInfo(user_info):
    data = request.get_json()
    user = User.query.filter_by(userid=data['userid']).first()
    if user is None:
        return Result.error(404, 'User not found')
    else:
        user.username = data['new_username']
        user.password = data['new_password']
        user.category = data['new_category']
        user.is_admin = data['new_is_admin']
        user.updateUser()
        return Result.success(user.to_dict())


# 添加用户
@api.route('/addUser', methods=['POST'])
@user_token_required(admin_required=True)
def addUser(user_info):
    data = request.json
    username = data['username']
    password = data['password']
    category = data['category']
    is_admin = data['is_admin']
    user = User(username, password, category, is_admin)
    user.addUser()


# 删除指定book
@api.route('/deleteBook/<bookid>', methods=['DELETE'])
@user_token_required(admin_required=True)
def deleteBook(bookid, user_info):
    book = Book.query.filter_by(bookid=bookid).first()
    if book is None:
        print('Book not found')
        return Result.error(404, 'Book not found')
    else:
        book.deleteBook()
        print('Book deleted')
        return Result.success(None, 'Book deleted')


# 添加书籍
@api.route('/addBook', methods=['POST'])
@user_token_required(admin_required=True)
def addBook(user_info):
    data = request.form
    bookname = data['bookname']
    author = data['author']
    press = data['press']
    surplus = data['surplus']
    category = data['category']
    price = data['price']

    pic = request.files.get('avatar')

    if pic is None:
        return Result.error(404, 'No Pic')
    else:
        if not os.path.exists('static/'):
            os.makedirs('static/')
            # 使用 os.path.join 来构建文件路径
        path = os.path.join("static/", bookname + ".jpg")
        pic.save(path)  # 保存

    book = Book(bookname, author, press, surplus, category, path, price)
    book.addBook()
    return Result.success(book.to_dict(), 'Book added')


# 修改图书信息
@api.route('/editBookInfo', methods=['PUT'])
@user_token_required(admin_required=True)
def editBookInfo(user_info):
    data = request.json
    bookid = data['bookid']
    bookname = data['bookname']
    author = data['author']
    press = data['press']
    surplus = data['surplus']
    category = data['category']
    price = data['price']

    book = Book.query.filter_by(bookid=bookid).first()
    book.update(bookname, author, press, surplus, category, price)
    return Result.success(None, 'Book updated')


# 获取用户咨询
@api.route('/getAllConsultations', methods=['GET'])
@user_token_required(admin_required=True)
def getAllConsultations(user_info):
    consultations = Consultation.query.all()
    if not consultations:
        return Result.error(404, 'no consultations')
    else:
        consult_list = []
        for consultation in consultations:
            consult_list.append(consultation.to_dict())
        return Result.success(consult_list)


# 获取未经处理的咨询
@api.route('/getUnprocessedConsultations', methods=['GET'])
@user_token_required(admin_required=True)
def getUnprocessedConsultations(user_info):
    consultations = Consultation.query.filter_by(is_processed=False).all()
    if not consultations:
        return Result.error(404, 'no unprocessed consultations')
    else:
        consult_list = []
        for consultation in consultations:
            consult_list.append(consultation.to_dict())
        return Result.success(consult_list)


# 获取已经处理的咨询
@api.route('/getProcessedConsultations', methods=['GET'])
@user_token_required(admin_required=True)
def getProcessedConsultation(user_info):
    consultations = Consultation.query.filter_by(is_processed=True).all()
    if not consultations:
        return Result.error(404, 'no processed consultations')
    else:
        consult_list = []
        for consultation in consultations:
            consult_list.append(consultation.to_dict())
        return Result.success(consult_list)


# 处理用户咨询
@api.route('/processConsultation', methods=['POST'])
@user_token_required(admin_required=True)
def processConsultation(user_info):
    data = request.json
    consultation_id = data['consultation_id']
    consultation = Consultation.query.filter_by(consultation_id=consultation_id).first()
    if consultation is None:
        return Result.error(404, 'Consultation not found')
    else:
        consultation.beProcessed()
        return Result.success(None, 'Consultation processed successfully')


# 接受前端发送的图片
@api.route('/ReceivePic/<bookname>', methods=['POST'])
def receivePic(bookname):
    # 请求中获取到上传的图片
    pic = request.files.get('avatar')
    book = Book.query.filter_by(bookname=bookname).first()
    if pic is None:
        return Result.error(404, 'No Pic')
    else:
        if book is None:
            return Result.error(404, 'Book not found')
        else:
            if not os.path.exists('static/'):
                os.makedirs('static/')
                # 使用 os.path.join 来构建文件路径
            path = os.path.join("static/", bookname + ".jpg")
            pic.save(path)  # 保存
            book.coverpath = path
            db.session.commit()
            return Result.success(path, 'Picture received')
